package com.example.qxfw.nyqx.service.impl;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.qxfw.backgroundManagement.service.WorkforceManagementService;
import com.example.qxfw.common.entity.xt.SysConfig;
import com.example.qxfw.common.entity.zy.AgriProduct;
import com.example.qxfw.common.util.DateUtil;
import com.example.qxfw.common.util.DocxUtil;
import com.example.qxfw.common.util.FileUtil;
import com.example.qxfw.mongodb.hy.entity.HyDocFile;
import com.example.qxfw.mongodb.hy.entity.HyPdfFile;
import com.example.qxfw.mongodb.hy.service.DocFileService;
import com.example.qxfw.mongodb.hy.service.PdfFileService;
import com.example.qxfw.nyqx.dto.WeekDocDto;
import com.example.qxfw.nyqx.dto.WeekTemplateDto;
import com.example.qxfw.nyqx.mapper.AgriProductMapper;
import com.example.qxfw.nyqx.service.NytqybService;
import com.example.qxfw.rcyw.pojo.JobMake;
import com.example.qxfw.ybzz.service.SysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.stereotype.Service;

import java.io.*;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class NytqybServiceImpl implements NytqybService {

    @Autowired
    private AgriProductMapper agriProductMapper;

    @Autowired
    private DocFileService docFileService;

    @Autowired
    private PdfFileService pdfFileService;

    @Autowired
    private WorkforceManagementService workforceManagementService;

    @Autowired
    private SysConfigService sysConfigService;


    @Override
    public WeekTemplateDto getWeekTemplate() throws IOException {
        ApplicationHome applicationHome = new ApplicationHome(FileUtil.class);
        String filepath = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath() + "\\src\\main\\resources\\Documents\\农用天气预报模板\\一周天气文档模板默认设置.txt";
        FileInputStream inputSteam = new FileInputStream(filepath);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputSteam));
        WeekTemplateDto weekTemplateDto = new WeekTemplateDto();
        bufferedReader.readLine();
        String trend = bufferedReader.readLine();
        weekTemplateDto.setTrend(trend);
        bufferedReader.readLine();
        String forecast = bufferedReader.readLine();
        weekTemplateDto.setForecast(forecast);
        bufferedReader.readLine();
        String element = bufferedReader.readLine();
        weekTemplateDto.setElement(element);
        bufferedReader.readLine();
        String advise = bufferedReader.readLine();
        weekTemplateDto.setAdvise(advise);

        return weekTemplateDto;
    }

    @Override
    public void createWeekDoc(WeekDocDto weekDocDto, String filename) throws ParseException {
        ApplicationHome applicationHome = new ApplicationHome(FileUtil.class);
        String resourcePath = "";
        if (filename.contains("月农用")) {
            resourcePath = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath() + "\\src\\main\\resources\\Documents\\农用天气预报\\农用月天气预报.docx";
        } else {
            resourcePath = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath() + "\\src\\main\\resources\\Documents\\农用天气预报\\农用天气预报.docx";
        }
        String targetPath = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath() + "\\src\\main\\resources\\temp\\" + filename + ".docx";
        String pdfTargetPath = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath() + "\\src\\main\\resources\\temp\\" + filename + ".pdf";
        String[] placeholders = new String[]{"[期数]", "[签发人]", "[标题]", "[时效]", "[天气趋势]", "[具体预报]", "[提示与建议]", "[联系电话]", "[年月日时]"};
        List<String> replacements = new ArrayList<>();
        replacements.add(weekDocDto.getIssueNumber());
        replacements.add(weekDocDto.getIssueUser());
        replacements.add(weekDocDto.getTitle());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日");
        Date nTimes1 = weekDocDto.getNTimes();
        Date nTimes2 = addDate(nTimes1, 7);
        replacements.add(dateFormat.format(nTimes1) + "~" + dateFormat.format(nTimes2));
        replacements.add(weekDocDto.getTrend());
        replacements.add(weekDocDto.getForecast());
        replacements.add(weekDocDto.getAdvise());
        replacements.add(weekDocDto.getPhone());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH时");
        replacements.add(simpleDateFormat.format(weekDocDto.getTime()));

        // maketime
        Timestamp timestampMake = DateUtil.localDateTimeToTimestamp(LocalDateTime.now());
        // forecasttime
        LocalDate currentDate = LocalDate.now();
        Timestamp timestampForcast = DateUtil.localDateTimeToTimestamp(currentDate.atStartOfDay());
        // 先获取表中是否已经又生成好的数据，有就直接查询将查询的结果返回，无则生成。
        AgriProduct product = agriProductMapper.selectOne(new LambdaQueryWrapper<AgriProduct>()
                .eq(AgriProduct::getProducttype, filename)
                .eq(AgriProduct::getForecasttime, timestampForcast)
                .eq(AgriProduct::getProductname, "气象服务信息-" + weekDocDto.getIssueNumber() + "-" + filename + ".docx"));
        if (product != null) {
            // 获取mongo库里的文档
            HyDocFile hyDocFile = docFileService.getByTableId(String.valueOf(product.getId()));
            // 如果文档存在就直接返回查询结果
            if (hyDocFile != null) {
                docFileService.deleteById(String.valueOf(product.getId()));
                // 如果表中有信息，文档不存在或表中无信息，就新生成一个文档并删除这条数据
                int i = agriProductMapper.deleteById(product.getId());
                InsertAgriProduct(weekDocDto.getIssueNumber(), filename, timestampForcast, timestampMake,
                        resourcePath, targetPath, placeholders, replacements, pdfTargetPath);
            } else {
                // 如果表中有信息，文档不存在或表中无信息，就新生成一个文档并删除这条数据
                int i = agriProductMapper.deleteById(product.getId());
                InsertAgriProduct(weekDocDto.getIssueNumber(), filename, timestampForcast, timestampMake,
                        resourcePath, targetPath, placeholders, replacements, pdfTargetPath);
            }
        } else {
            // 文档信息，先存入表agri_product
            InsertAgriProduct(weekDocDto.getIssueNumber(), filename, timestampForcast, timestampMake,
                    resourcePath, targetPath, placeholders, replacements, pdfTargetPath);
        }
        JobMake jobMake = new JobMake();
        jobMake.setJobname(filename);
        jobMake.setNametype("农业气象");
        jobMake.setRecentmaketime(DateTime.now());
        workforceManagementService.updateJobMark2(jobMake);
        String paramName = "";
        //更新数据库里面的期号
        if (filename.contains("周")) {
            paramName = "dm_AgrWeekDocNumber";
        } else if (filename.contains("月")) {
            paramName = "dm_AgrMonthDocNumber";
        } else if (filename.contains("灾害")) {
            paramName = "dm_AgrDisDocNumber";
        }
        SysConfig config = new SysConfig();
        config.setParamname(paramName);
        if(weekDocDto.getIssueNumber().contains("年") && weekDocDto.getIssueNumber().contains("期")) {
            String docNum = weekDocDto.getIssueNumber().split("年")[1].split("期")[0];
            config.setParamvalue(String.valueOf(Integer.parseInt(docNum) + 1));
        }
        sysConfigService.updateByParamName(config);
    }

    private void InsertAgriProduct(String issueNumber, String filename, Timestamp timestampForcast, Timestamp timestampMake,
                                   String resourcePath, String targetPath, String[] placeholders, List<String> replacements,
                                   String pdfTargetPath) {
        // 文档信息，先存入表agri_product
        AgriProduct agriProduct = new AgriProduct();
        agriProduct.setProductname("玉林-气象服务信息-" + issueNumber + "-" + filename + ".docx");
        agriProduct.setProducttype(filename);
        agriProduct.setForecasttime(timestampForcast);
        agriProduct.setMaketime(timestampMake);
        agriProduct.setMaker("admin");
        agriProduct.setState("0");
        agriProduct.setShflag(null);
        agriProduct.setShidea(null);
        int insert = agriProductMapper.insert(agriProduct);
        // 数据插入后，再执行文档的生成
        if (insert > 0) {
            DocxUtil.generateWordDocx(resourcePath, targetPath, placeholders, replacements.toArray(new String[replacements.size()]));
            // 将生成的文档保存入mg数据库
            File docxFile = new File(targetPath);
            // 判断文档是否已经生成完毕
            if (docxFile.exists()) {
                //文件保存入数据库
                HyDocFile file = new HyDocFile();
                try {
                    byte[] bytes = DocxUtil.readDocxFileToByteArray(targetPath);
                    file.setData(bytes);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                file.setId(String.valueOf(agriProduct.getId()));
                file.setTable_name("agri_product");
                file.setName(agriProduct.getProducttype() + ".docx");
                docFileService.save(file);

                //生成pdf文档并返回url
                System.err.println("pdfPath:" + pdfTargetPath);
                DocxUtil.wordToPdf(targetPath, pdfTargetPath);
                //文件保存入数据库
                HyPdfFile pdffile = new HyPdfFile();
                try {
                    byte[] bytes = DocxUtil.readDocxFileToByteArray(pdfTargetPath);
                    pdffile.setData(bytes);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                pdffile.setId(String.valueOf(agriProduct.getId()));
                pdffile.setTable_name("agri_product");
                pdffile.setName(agriProduct.getProducttype() + ".pdf");
                pdfFileService.save(pdffile);
            } else {
                // 文件生成失败，可以抛出异常或者执行其他处理逻辑
                throw new RuntimeException("生成docx文件失败！");
            }
        }
    }

    @Override
    public WeekTemplateDto getMonthTemplate() throws IOException {
        ApplicationHome applicationHome = new ApplicationHome(FileUtil.class);
        String filepath = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath() + "\\src\\main\\resources\\Documents\\农用天气预报模板\\月农用天气预报文档模板默认设置.txt";
        FileInputStream inputSteam = new FileInputStream(filepath);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputSteam));
        WeekTemplateDto weekTemplateDto = new WeekTemplateDto();
        bufferedReader.readLine();
        String trend = bufferedReader.readLine();
        weekTemplateDto.setTrend(trend);
        bufferedReader.readLine();
        String forecast = bufferedReader.readLine();
        weekTemplateDto.setForecast(forecast);
        bufferedReader.readLine();
        String element = bufferedReader.readLine();
        weekTemplateDto.setElement(element);
        bufferedReader.readLine();
        String advise = bufferedReader.readLine();
        weekTemplateDto.setAdvise(advise);

        return weekTemplateDto;
    }

    @Override
    public WeekTemplateDto getQxWarnTemplate() throws IOException {
        ApplicationHome applicationHome = new ApplicationHome(FileUtil.class);
        String filepath = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath() + "\\src\\main\\resources\\Documents\\农用天气预报模板\\农业气象灾害预警文档模板默认设置.txt";
        FileInputStream inputSteam = new FileInputStream(filepath);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputSteam));
        WeekTemplateDto weekTemplateDto = new WeekTemplateDto();
        bufferedReader.readLine();
        String trend = bufferedReader.readLine();
        weekTemplateDto.setTrend(trend);
        bufferedReader.readLine();
        String forecast = bufferedReader.readLine();
        weekTemplateDto.setForecast(forecast);
        bufferedReader.readLine();
        String advise = bufferedReader.readLine();
        weekTemplateDto.setAdvise(advise);

        return weekTemplateDto;
    }

    @Override
    public HyPdfFile getLastWeekDoc(String type) {
        List<AgriProduct> agrilist = agriProductMapper.selectIdByProducttype(type);
        for (AgriProduct agri : agrilist) {
            // 获取mongo库里的文档
            HyPdfFile hyDocFile = pdfFileService.getByTableId(String.valueOf(agri.getId()));
            return hyDocFile;
        }
        return null;
    }

    public Date addDate(Date date, long day) throws ParseException {
        long time = date.getTime(); // 得到指定日期的毫秒数
        day = day * 24 * 60 * 60 * 1000; // 要加上的天数转换成毫秒数
        time += day; // 相加得到新的毫秒数
        return new Date(time); // 将毫秒数转换成日期
    }

}
